package com.example.girl.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.example.girl.activity.BaiDuActivity;
import com.example.girl.bean.Constants;
import com.example.girl.bean.Constants2;
import com.example.girl.activity.PhotoActivity;
import com.example.girl.activity.ContentActivity;
import com.example.girl.adapter.EsayGirlAdapter;
import com.example.girl.bean.BBB;
import com.example.girl.http.APIRetrofit;
import com.example.girl.http.APIService;
import com.example.girl.model.GirlResult;
import com.example.girl.util.DensityUtil;
import com.example.girl.util.SpfUtils;
import com.example.lbstest.R;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.jude.easyrecyclerview.decoration.SpaceDecoration;
import com.king.base.BaseFragment;
import com.king.base.model.EventMessage;
import com.king.base.util.LogUtils;
import com.king.base.util.SharedPreferencesUtils;
import com.king.base.util.SystemUtils;


import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * @author Jenly <a href="mailto:jenly1314@gmail.com">Jenly</a>
 * @since 2017/1/11
 */
public class GirlsFragment extends BaseFragment implements PhotoActivity.OnScrollListener {


    public enum LayoutType {
        LinearLayout, GridLayout, StaggeredGridLayout
    }

    private LayoutType layoutType = LayoutType.StaggeredGridLayout;

    private static final int PAGE_SIZE = 10;

    private TextView tvTips;

    private EasyRecyclerView recyclerView;

    private EsayGirlAdapter esayGirlAdapter;

    private List<GirlResult.RowsBean> listData;

    private int curPage;
    private String type;

    public static GirlsFragment newInstance(LayoutType layoutType, String type) {

        Bundle args = new Bundle();

        GirlsFragment fragment = new GirlsFragment();
        fragment.setArguments(args);
        fragment.layoutType = layoutType;
        fragment.type = type;
        return fragment;
    }

    @Override
    public void onScroll() {
        if (recyclerView != null)
            recyclerView.scrollToPosition(0);
    }

    @Override
    public int inflaterRootView() {
        return R.layout.fragment_girl;
    }

    @Override
    public void initUI() {

        recyclerView = findView(R.id.recyclerView);

        tvTips = (TextView) recyclerView.findViewById(R.id.tvTips);

        listData = new ArrayList<>();
        esayGirlAdapter = new EsayGirlAdapter(context, listData, layoutType == LayoutType.GridLayout);

        initLayoutManager(layoutType);

        SpaceDecoration spaceDecoration = new SpaceDecoration(DensityUtil.dp2px(context, 2));
        recyclerView.addItemDecoration(spaceDecoration);
//        recyclerView.setRefreshingColor(R.color.colorPrimary);
        recyclerView.setRefreshingColorResources(R.color.colorPrimary);

        recyclerView.setAdapter(esayGirlAdapter);

        esayGirlAdapter.setMore(R.layout.load_more, new RecyclerArrayAdapter.OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                Log.e("111", "当前页面：" + curPage);


                if (curPage >= 10) {

                    getGirls3();
                } else {
                    getGirls(curPage, PAGE_SIZE);
                }

            }
        });



    }

    private void initLayoutManager(LayoutType layoutType) {
        switch (layoutType) {
            case LinearLayout:
                recyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
                break;
            case GridLayout:
                GridLayoutManager gridLayoutManager = new GridLayoutManager(context, 2);
                gridLayoutManager.setSpanSizeLookup(esayGirlAdapter.obtainGridSpanSizeLookUp(2));
                recyclerView.setLayoutManager(gridLayoutManager);
                break;
            case StaggeredGridLayout:
            default:
                final StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
                staggeredGridLayoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
                recyclerView.setLayoutManager(staggeredGridLayoutManager);
                recyclerView.getRecyclerView().addOnScrollListener(new RecyclerView.OnScrollListener() {
                    @Override
                    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                        super.onScrollStateChanged(recyclerView, newState);
                        //防止第一行到顶部有空白区域
                        staggeredGridLayoutManager.invalidateSpanAssignments();
                    }
                });
                break;
        }
    }

    @Override
    public void addListeners() {

        recyclerView.setRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                curPage = 1;
                getGirls(curPage, PAGE_SIZE);
            }
        });

        esayGirlAdapter.setOnClickHolderItemListener(new EsayGirlAdapter.OnClickHolderItemListener() {
            @Override
            public void onItemClick(BaseViewHolder holder, int position) {
                GirlResult.RowsBean rowsBean = list.get(position);
                tipClick(rowsBean.getFlower_name(),rowsBean.getRecommend());
//                startGirlDetail((ArrayList<GirlResult.RowsBean>) esayGirlAdapter.getAllData(), position, holder.itemView);
            }
        });

    }

    /**
     * @param listData
     * @param position
     * @param source
     */
    private void startGirlDetail(ArrayList<GirlResult.RowsBean> listData, int position, View source) {
        Intent intent = new Intent(context, ContentActivity.class);
        intent.putExtra(KEY_FRAGMENT, ContentActivity.GIRL_DETAIL_FRAGMENT);
        intent.putParcelableArrayListExtra(Constants.LIST_GIRL, listData);
        intent.putExtra(Constants.CURRENT_POSTION, position);

        ActivityOptionsCompat activityOptionsCompat = ActivityOptionsCompat.makeScaleUpAnimation(source, source.getWidth() / 2, source.getHeight() / 2, 0, 0);
        ActivityCompat.startActivity(getActivity(), intent, activityOptionsCompat.toBundle());
    }


    @Override
    public void initData() {

        curPage = 1;
        getGirls(curPage, PAGE_SIZE);

    }


    private <T> void toSetList(List<T> list, List<T> newList, boolean isMore) {

        if (list == null || newList == null)
            return;

        if (!isMore) {
            list.clear();
        }
        list.addAll(newList);

    }

    List<GirlResult.RowsBean> list;
    private void getGirls(final int page, final int size) {
        Log.e("111", "page:"+page);
        Log.e("111", "type:"+type);
        APIRetrofit.getInstance()
                .create(APIService.class)
                .getGirs(type, size, page)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<GirlResult>() {
                    @Override
                    public void onCompleted() {
                        LogUtils.d("onCompleted");
                        recyclerView.setRefreshing(false);
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtils.e(e);

                        if (SystemUtils.isNetWorkActive(context)) {
                            tvTips.setText(R.string.page_load_failed);
                        } else {
                            tvTips.setText(R.string.network_unavailable);
                        }

                        recyclerView.showError();
                    }

                    @Override
                    public void onNext(GirlResult girlResult) {
                        LogUtils.e(girlResult.toString());
                        Log.e("111", "" + girlResult.toString());
                        if (girlResult != null) {
//
                            list = girlResult.getRows();
                            if (page <= 1) {
                                esayGirlAdapter.clear();
                                if (list != null && list.size() > 0) {
                                    SharedPreferencesUtils.put(context, Constants.FIRST_GIRL_URL, list.get(0).getFlower_photo());
                                }
                            }
                            esayGirlAdapter.addAll(girlResult.getRows());
//                            refreshView();
                            if (esayGirlAdapter.getCount() >= page * size) {
                                Log.e("1111", "A"+esayGirlAdapter.getCount());
                                Log.e("1111", "b"+(page * size));
                                curPage++;
                                Log.e("1111", "xx"+5858);
                            } else if (esayGirlAdapter.getCount() == 0) {
                                recyclerView.showEmpty();
                            }else {
                                Log.e("1111", "xx"+5959);
                                Log.e("1111", "C"+esayGirlAdapter.getCount());
                                Log.e("1111", "D"+(page * size));
                                esayGirlAdapter.stopMore();
                                esayGirlAdapter.setNoMore(R.layout.about_me_layout2);
                            }
//
                        } else {
                            recyclerView.showEmpty();

                        }
                    }
                });
    }


    @Override
    public void onEventMessage(EventMessage em) {

    }


    private void getGirls3() {
        String acc = (String) SpfUtils.get(getActivity(), "acc", "123");

        APIRetrofit.getInstance()
                .create(APIService.class)
                .quanxian(acc)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BBB>() {
                    @Override
                    public void onCompleted() {
                        LogUtils.d("onCompleted");

                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtils.e(e);
                        Toast.makeText(getActivity(), "网络错误!", Toast.LENGTH_SHORT).show();


                    }

                    @Override
                    public void onNext(BBB girlResult) {
                        LogUtils.d(girlResult.toString());
                        if (girlResult != null) {
                            String userNm = girlResult.getData().getUserNm();

                                Log.e("1111", "请求数据了");
                                getGirls(curPage, PAGE_SIZE);




                        }
                    }
                });
    }


    /**
     * 提示对话框
     *
     * @param view
     */
    public void tipClick(final  String NAEM,String jianjie) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("简介");
        builder.setMessage(jianjie);

        //点击对话框以外的区域是否让对话框消失
        builder.setCancelable(true);
        //设置正面按钮
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.setNegativeButton("导航", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                startActivity(new Intent(getActivity(), BaiDuActivity.class).putExtra("name",NAEM));
            }
        });


        AlertDialog dialog = builder.create();

        //显示对话框
        dialog.show();
    }


}
